﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Drawing.Printing;
using System.Security.Cryptography;

namespace WFTest
{
    public partial class Mations : Form
    {
        string meage = string.Empty;

        #region DLL库
        [DllImport("dcrf32.dll")]
        public static extern int dc_init(Int16 port, Int32 baud);  //初试化
        [DllImport("dcrf32.dll")]
        public static extern short dc_exit(int icdev);
        [DllImport("dcrf32.dll")]
        public static extern short dc_beep(int icdev, ushort misc);
        [DllImport("dcrf32.dll")]
        public static extern short dc_reset(int icdev, uint sec);
        [DllImport("dcrf32.dll")]
        public static extern short dc_config_card(int icdev, byte cardType);
        [DllImport("dcrf32.dll")]

        public static extern short dc_card(int icdev, byte model, ref ulong snr);

        [DllImport("dcrf32.dll")]
        public static extern short dc_card_double(int icdev, byte model, [Out] byte[] snr);

        [DllImport("dcrf32.dll")]
        public static extern short dc_card_double_hex(int icdev, byte model, [Out]char[] snr);

        [DllImport("dcrf32.dll")]
        public static extern short dc_pro_reset(int icdev, ref byte rlen, [Out] byte[] recvbuff);
        [DllImport("dcrf32.dll")]
        public static extern short dc_pro_command(int icdev, byte slen, byte[] sendbuff, ref byte rlen,
                                                     [Out]byte[] recvbuff, byte timeout);
        [DllImport("dcrf32.dll")]
        public static extern short dc_card_b(int icdev, [Out] byte[] atqb);


        [DllImport("dcrf32.dll")]
        public static extern short dc_setcpu(int icdev, byte address);
        [DllImport("dcrf32.dll")]
        public static extern short dc_cpureset(int icdev, ref byte rlen, byte[] rdata);
        [DllImport("dcrf32.dll")]
        public static extern short dc_cpuapdu(int icdev, byte slen, byte[] sendbuff, ref byte rlen,
                                                     [Out]byte[] recvbuff);

        [DllImport("dcrf32.dll")]
        public static extern short dc_readpincount_4442(int icdev);
        [DllImport("dcrf32.dll")]
        public static extern short dc_read_4442(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_write_4442(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_verifypin_4442(int icdev, byte[] password);
        [DllImport("dcrf32.dll")]
        public static extern short dc_readpin_4442(int icdev, byte[] password);
        [DllImport("dcrf32.dll")]
        public static extern short dc_changepin_4442(int icdev, byte[] password);

        [DllImport("dcrf32.dll")]
        public static extern short dc_readpincount_4428(int icdev);
        [DllImport("dcrf32.dll")]
        public static extern short dc_read_4428(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_write_4428(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_verifypin_4428(int icdev, byte[] password);
        [DllImport("dcrf32.dll")]
        public static extern short dc_readpin_4428(int icdev, byte[] password);
        [DllImport("dcrf32.dll")]
        public static extern short dc_changepin_4428(int icdev, byte[] password);

        [DllImport("dcrf32.dll")]
        public static extern int dc_authentication(int icdev, int _Mode, int _SecNr);

        [DllImport("dcrf32.dll")]
        public static extern int dc_authentication_pass(int icdev, int _Mode, int _SecNr, byte[] nkey);

        [DllImport("dcrf32.dll")]
        public static extern int dc_authentication_pass_hex(int icdev, int _Mode, int _SecNr, string nkey);

        [DllImport("dcrf32.dll")]
        public static extern int dc_load_key(int icdev, int mode, int secnr, byte[] nkey);  //密码装载到读写模块中


        [DllImport("dcrf32.dll")]
        public static extern int dc_write(int icdev, int adr, [In] byte[] sdata);  //向卡中写入数据

        [DllImport("dcrf32.dll")]
        public static extern int dc_write_hex(int icdev, int adr, [In] string sdata);  //向卡中写入数据


        [DllImport("dcrf32.dll")]
        public static extern int dc_read(int icdev, int adr, [Out] byte[] sdata);  //从卡中读数据

        [DllImport("dcrf32.dll")]
        public static extern short dc_read_24c(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_write_24c(int icdev, Int16 offset, Int16 lenth, byte[] buffer);

        [DllImport("dcrf32.dll")]
        public static extern short dc_read_24c64(int icdev, Int16 offset, Int16 lenth, byte[] buffer);
        [DllImport("dcrf32.dll")]
        public static extern short dc_write_24c64(int icdev, Int16 offset, Int16 lenth, byte[] buffer);

        #endregion
        public Mations()
        {
            InitializeComponent();
        }
        #region 数据库连接
        string uname = userInfo.userName;
        static string sqlcon = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
        SqlConnection conn = new SqlConnection(sqlcon);
      

        //打开连接
        protected void OpenConn()
        {
            try
            {
                if (this.conn.State != ConnectionState.Open)
                    conn.Open();
            }
            catch (SqlException e) { throw e; }
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseConn()
        {
            if (this.conn != null && this.conn.State == ConnectionState.Open)
                this.conn.Close();
        }
        #endregion

        #region 建卡
        //MD5加密
        class Encrypt
        {
            public string str2 = "";//记录加密后的数值
            public Encrypt(string str)
            {
                MD5 md5 = new MD5CryptoServiceProvider();//创建MD5对象（MD5类为抽象类不能被实例化）
                byte[] date = System.Text.Encoding.Default.GetBytes(str);//将字符串编码转换为一个字节序列
                byte[] date1 = md5.ComputeHash(date);//计算data字节数组的哈希值（加密）
                md5.Clear();//释放类资源
                for (int i = 0; i < date1.Length - 1; i++)//遍历加密后的数值到变量str2
                {
                    str2 += date1[i].ToString("X");//（X为大写时加密后的数值里的字母为大写，x为小写时加密后的数值里的字母为小写）
                }
            }
        }

        //读卡
        private void jkcardread_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                int icdev;
                int st;
                //初始化
                icdev = dc_init(100, 115200);
                if (icdev < 0)
                {
                    return;
                }
                //蜂鸣
                st = dc_beep(icdev, 10);

                st = dc_config_card(icdev, 0x41);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }

                //2.射频读卡器复位
                st = dc_reset(icdev, 10);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }

                //3.寻卡
                char[] rbuf = new char[128];
                st = dc_card_double_hex(icdev, 0, rbuf);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }
                dc_exit(icdev);
                jkcardid.Text = new string(rbuf);
                jkcardno.Text = "";
                jkcardname.Text = "";
                jkphone.Text = "";
                jkadress.Text = "";
                try
                {
                    int count = 0;
                    if (jkCardpwd.Text == "")
                    {
                        MessageBox.Show("请输入密码!");
                    }
                    else
                    {
                        string str = string.Format("select Cardpwd from Cardmation where CardId='{0}'", jkcardid.Text);
                        SqlDataAdapter sda = new SqlDataAdapter(str, conn);
                        DataTable dt1 = new DataTable();
                        sda.Fill(dt1);
                        Encrypt en = new Encrypt(jkCardpwd.Text);//实例化Encrypt
                        if (dt1.Rows[0]["Cardpwd"].ToString() == en.ToString())
                        {
                            SqlParameter[] param = new SqlParameter[]
                               {
                                  new SqlParameter( "@CardId", new string(rbuf))
                               };
                            DataTable dt = DBHelper.ExecuteQuery("ReadCardId", param, CommandType.StoredProcedure);
                            jkcardno.Text = dt.Rows[0]["CardNo"].ToString();
                            jkcardname.Text = dt.Rows[0]["CardName"].ToString();
                            jkphone.Text = dt.Rows[0]["phone"].ToString();
                            jkadress.Text = dt.Rows[0]["adress"].ToString();
                            jkcardid.ReadOnly = true;
                            jksunmoney.Text = dt.Rows[0]["Cardmoney"].ToString();
                            jkthecard.Enabled = jkcancel.Enabled = jkquery.Enabled = true;
                        }
                        else
                        {
                            MessageBox.Show("密码输入错误!");
                            count++;
                            if(count==3)
                            {
                                MessageBox.Show("你已经输入三次，请24小时后再输入!");
                            
                            jkthecard.Enabled = jkcancel.Enabled = jkquery.Enabled = jkconcellation.Enabled = jkrecharge.Enabled = jkchange.Enabled = jkfillcard.Enabled = jkcheck.Enabled =
                            xfcardread.Enabled = xfconfirm.Enabled = xfcancel.Enabled = xfquery.Enabled= false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);

                }
                jkthecard.Enabled = jkcancel.Enabled  = jkrecharge.Enabled = true;
                
            }
        }
        public void JKCard()
        {
            Encrypt Cardpwd = new Encrypt(jkCardpwd.Text.Trim());//实例化Encrypt
            SqlParameter[] param = new SqlParameter[] {
                new SqlParameter("@CardNo",jkcardno.Text.Trim()),
                new SqlParameter("@CardName",jkcardname.Text.Trim()),
                new SqlParameter("@phone",jkphone.Text.Trim()),
                new SqlParameter("@adress",jkadress.Text.Trim()),
                new SqlParameter("@Cardmoney",jkmoney.Text.Trim()),
                new SqlParameter("@xf_money",jkmoney.Text.Trim()),
                new SqlParameter("@Cardpwd",Cardpwd )
            };
            
            int i = DBHelper.ExecuteNonQuery("TheCards", param, CommandType.StoredProcedure);
            if (i > 0 )
            {
                MessageBox.Show("账户:" + jkcardno.Text + "\n用户名:" + jkcardname.Text + "\n金额:" + jkmoney.Text + "");
            }
        }
        //建卡
        private void jkthecard_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                try
                {
                    OpenConn();
                    string str2 = string.Format("select top 1 a.type from Cardmation a join typemation b on a.type=b.type_code where a.CardId='{0}' order by a.id desc", jkcardid.Text);
                    SqlDataAdapter sda = new SqlDataAdapter(str2, conn);

                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["type"].ToString() == "2")
                        {
                            return;
                        }
                        else
                        {
                            JKCard();
                        }
                    }
                    if (dt.Rows.Count == 0)
                    {
                        JKCard();
                    }
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    conn.Close();
                }
                CloseConn();
                jkquery.Enabled = true;
            }
        }
        //取消
        private void jkcancel_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                jkcardid.Text = jkcardname.Text = jkphone.Text = jkadress.Text = jkmoney.Text = "";
            }
        }
        //查询
        private void jkquery_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@CardNo",jkcardno.Text),
                    new SqlParameter("@phone",""),
                    new SqlParameter("@code","1")
                };
                DataTable dt = DBHelper.ExecuteQuery("QueryCard", param, CommandType.StoredProcedure);
                this.printDocument2.DefaultPageSettings.PaperSize = new PaperSize("Custum", 1200, 800);
                this.printDocument2.PrintPage += new PrintPageEventHandler(this.printDocument1_PrintPage);

                jkcardno.Text = dt.Rows[0]["CardNo"].ToString();
                jkcardname.Text = dt.Rows[0]["CardName"].ToString();
                jkphone.Text = dt.Rows[0]["phone"].ToString();
                jkadress.Text = dt.Rows[0]["adress"].ToString();
                jkcardid.ReadOnly = jkcardname.ReadOnly = jkphone.ReadOnly = jkadress.ReadOnly = true;

                meage = string.Empty;
                meage=("----------账户余额---------\n\n账户:" + jkcardno.Text + "\n持卡人:" + jkcardname.Text + "\n余额:" + dt.Rows[0]["Cardmoney"].ToString() + "\n\n\n\n\n___________________________________");
                MessageBox.Show(meage);

                this.printDocument2.Print();
            }
        }

        //注销
        private void jkconcellation_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@username",uname),
                    new SqlParameter("@CardNo",jkcardno.Text),
                    new SqlParameter("@CardName",""),
                    new SqlParameter("@phone",jkphone.Text),
                    new SqlParameter("@adress",""),
                    new SqlParameter("@code",1)
                };
                int i = DBHelper.ExecuteNonQuery("JurisdictionName", param, CommandType.StoredProcedure);
                    if (i > 0)
                    {
                        MessageBox.Show("此卡已被注销!");
                    }
                    jkcardno.Text = "";
                    jkcardname.Text = "";
                    jkphone.Text = "";
                    jkadress.Text = "";
                    jkmoney.Text = "";
            }
        }

        //补卡
        private void jkfillcard_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                SqlParameter[] param = new SqlParameter[]
                {
                 new SqlParameter( "@CardNo", ""),
                 new SqlParameter("@phone",jkphone.Text),
                 new SqlParameter("@code", "3")
                };
                DataTable dt = DBHelper.ExecuteQuery("QueryCard", param, CommandType.StoredProcedure);
                jkcardno.Text = dt.Rows[0]["CardNo"].ToString();
                jkcardname.Text = dt.Rows[0]["CardName"].ToString();
                jkadress.Text = dt.Rows[0]["adress"].ToString();
                jksunmoney.Text = dt.Rows[0]["Cardmoney"].ToString();
                jkconcellation.Enabled = true;
                jkcardname.Enabled = false;
                jkadress.Enabled = false;
                MessageBox.Show("账户:'" + jkcardno.Text + "'\n用户名:'" + jkcardname.Text + "'\n联系方式:'" + jkphone.Text + "'\n地址:'" + jkadress.Text + "'\n余额:'" + jksunmoney.Text + "'");
            }
        }
        //充值
        private void jkrecharge_Click_1(object sender, EventArgs e)
        {
           if(this.tabControl1.SelectedTab.Text == "建卡")
            {
                int iYE = Convert.ToInt32(jksunmoney.Text) + Convert.ToInt32(jkmoney.Text);
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@CardNo",jkcardno.Text),
                    new SqlParameter("@Cardmoney",iYE),
                    new SqlParameter("@xf_money",jkmoney.Text)
                };
                int i = DBHelper.ExecuteNonQuery("FillRechargeCard", param, CommandType.StoredProcedure);
                if (i > 0 )
                {
                    MessageBox.Show("充值成功!");
                    jkmoney.Text = "";
                }
            }
        }
        //查
        private void jkcheck_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {

                SqlParameter[] param = new SqlParameter[]
                {
                 new SqlParameter( "@CardNo", jkcardno.Text),
                 new SqlParameter("@phone",""),
                 new SqlParameter("@code", "2")
                 };
                DataTable dt = DBHelper.ExecuteQuery("QueryCard", param, CommandType.StoredProcedure);
                jkcardname.Text = dt.Rows[0]["CardName"].ToString();
                jkphone.Text = dt.Rows[0]["phone"].ToString();
                jkadress.Text =dt.Rows[0]["adress"].ToString();
                jkchange.Enabled = true;
            }
        }
        //改
        private void jkchange_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@username",uname),
                    new SqlParameter("@CardNo",jkcardno.Text),
                    new SqlParameter("@CardName",jkcardname.Text),
                    new SqlParameter("@phone",jkphone.Text),
                    new SqlParameter("@adress",jkadress.Text),
                    new SqlParameter("@code","2")
                };
                int i = DBHelper.ExecuteNonQuery("JurisdictionName", param, CommandType.StoredProcedure);
                    if (i > 0)
                    {
                        MessageBox.Show("账号:'" + jkcardno.Text + "'\n信息已修改成功!");
                    }
            }
        }

        private void tabPage1_Click_1(object sender, EventArgs e)
        {
            jkthecard.Enabled = jkcancel.Enabled = jkquery.Enabled = false;
        }

        private void printDocument2_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (!string.IsNullOrEmpty(meage))
            {
                e.Graphics.DrawString(meage, new Font(new FontFamily("微软雅黑"), 9), System.Drawing.Brushes.Black, 2, 2);
            }
        }
        #endregion

        #region 消费
        public bool sdk_read(DataTable dt)
        {
            bool flg = false;

            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["type"].ToString() == "2")
                {
                    flg = true;
                }

            }
            else
            {
                flg = true;
            }


            return flg;
        }
        //读卡
        private void xfcardread_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "消费")
            {
                int icdev;
                int st;
                //初始化
                icdev = dc_init(100, 115200);
                if (icdev < 0)
                {
                    return;
                }
                //蜂鸣
                st = dc_beep(icdev, 10);

                st = dc_config_card(icdev, 0x41);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }

                //2.射频读卡器复位
                st = dc_reset(icdev, 10);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }

                //3.寻卡
                char[] rbuf = new char[128];
                st = dc_card_double_hex(icdev, 0, rbuf);
                if (st != 0)
                {
                    dc_exit(icdev);
                    return;
                }
                dc_exit(icdev);
                xfCardNo.Text = new string(rbuf);

                try
                {

                    conn.Open();
                    string str = string.Format("select top 1 CardNo,type,CardName,adress,phone from Cardmation where CardId='{0}' order by id desc", new string(rbuf));
                    SqlDataAdapter sda = new SqlDataAdapter(str, conn);
                    DataTable dt = new System.Data.DataTable();
                    sda.Fill(dt);
                    if (!sdk_read(dt))
                    {

                        xfCardNo.Text = dt.Rows[0]["CardNo"].ToString();
                        xfcardname.Text = dt.Rows[0]["CardName"].ToString();
                        xfphone.Text = dt.Rows[0]["phone"].ToString();
                        xfadress.Text = dt.Rows[0]["adress"].ToString();
                        conn.Close();
                        xfCardNo.ReadOnly = xfcardname.ReadOnly = xfphone.ReadOnly = xfadress.ReadOnly = true;
                        xfconfirm.Enabled = xfcancel.Enabled = xfquery.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("无此卡信息！请联系管理员。");
                        xfCardNo.Text = "";
                        xfcardname.Text = "";
                        xfphone.Text = "";
                        xfadress.Text = "";
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    conn.Close();
                }
                conn.Close();
            }
        }

        //消费确认
        private void xfconfirm_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "消费")
            {
                if (xfmoney.Text == "")
                {
                    MessageBox.Show("请输入消费金额!");
                }
                else
                {
                    conn.Open();
                    string str1 = string.Format("select Cardmoney from Cardset where CardNo='{0}'", xfCardNo.Text);
                    SqlDataAdapter sda = new SqlDataAdapter(str1, conn);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    if (Convert.ToInt32(dt.Rows[0]["Cardmoney"].ToString()) < Convert.ToInt32(xfmoney.Text))
                    {
                        MessageBox.Show("余额不足\n卡号:" + xfCardNo.Text + "\n请及时充值");
                        return;
                    }
                    else
                    {

                        SqlParameter[] param = new SqlParameter[] {
                        new SqlParameter("@Cardno",xfCardNo.Text),
                        new SqlParameter("@xf_money",xfmoney.Text)
                    };
                        int i = DBHelper.ExecuteNonQuery("ConsumptionMoney", param, CommandType.StoredProcedure);
                        this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", 1200, 800);
                        this.printDocument1.PrintPage += new PrintPageEventHandler(this.printDocument1_PrintPage);
                        if (i > 0 )
                        {
                            meage = string.Empty;
                            meage = "----------消费凭证---------\n\n卡号:" + xfCardNo.Text + "\n用户名:" + xfcardname.Text + "\n消费金额:" + xfmoney.Text + "元\n余额:" + (Convert.ToInt32(dt.Rows[0]["Cardmoney"].ToString()) - Convert.ToInt32(xfmoney.Text)) + "元\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\n\n\n\n\n___________________________________";
                            MessageBox.Show(meage);
                            
                            this.printDocument1.Print();
                            this.printDocument1.Print();
                        }
                    }
                    conn.Close();
                    xfCardNo.Text = "";
                    xfcardname.Text = "";
                    xfphone.Text = "";
                    xfadress.Text = "";
                    xfmoney.Text = "";
                }
            }
        }
        //取消消费
        private void xfcancel_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "消费")
            {
                xfCardNo.Text = xfcardname.Text = xfphone.Text = xfadress.Text = xfmoney.Text = "";
            }
        }
        //查询
        private void xfquery_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "消费")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@CardNo",xfCardNo.Text)
                };
                DataTable dt = DBHelper.ExecuteQuery("ConsumerQuery", param, CommandType.StoredProcedure);
                xfCardNo.Text = dt.Rows[0]["CardNo"].ToString();
                xfcardname.Text = dt.Rows[0]["CardName"].ToString();
                xfphone.Text = dt.Rows[0]["phone"].ToString();
                xfadress.Text = dt.Rows[0]["adress"].ToString();
                string cardmoney = dt.Rows[0]["Cardmoney"].ToString();
                xfCardNo.ReadOnly = xfcardname.ReadOnly = xfphone.ReadOnly = xfadress.ReadOnly = true;

                MessageBox.Show("卡号:" + xfCardNo.Text + "\n持卡人:" + xfcardname.Text + "\n余额:" + cardmoney + "");
                conn.Close();
            }
        }
        
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            if (!string.IsNullOrEmpty(meage))
            {
                e.Graphics.DrawString(meage, new Font(new FontFamily("微软雅黑"), 9), System.Drawing.Brushes.Black, 2, 2);
            }
        }


        #endregion

        #region 查询打印
        public void Query_print()
        {
            if (this.tabControl1.SelectedTab.Text == "查询打印")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@CardNo",cxcardno.Text),
                    new SqlParameter("@mationtype",cxtype.SelectedValue.ToString()),
                    new SqlParameter("@xfstartdate",cxstartdate.Text.ToString()),
                    new SqlParameter("@xfenddate",cxenddate.Text.ToString())
                };
                DataTable dt = DBHelper.ExecuteQuery("CardQuery_print", param, CommandType.StoredProcedure);
                dataGridView1.DataSource = dt.DefaultView;
            }
        }
        //查询
        private void cxquery_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "查询打印")
            {
                Query_print();
            }
        }

        //导出execl文件
        private void cxexport_Click_1(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "查询打印")
            {
                SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@CardNo",cxcardno.Text),
                    new SqlParameter("@mationtype",cxtype.SelectedValue.ToString()),
                    new SqlParameter("@xfstartdate",cxstartdate.Text.ToString()),
                    new SqlParameter("@xfenddate",cxenddate.Text.ToString())
                };
                DataTable dt = DBHelper.ExecuteQuery("CardQuery_print", param, CommandType.StoredProcedure);
                
                if (dt == null) return;
                System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
                saveFileDlg.Title = "导出过程数据";
                saveFileDlg.Filter = "过程数据(*.xls)|*.xls";
                saveFileDlg.RestoreDirectory = true;
                if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string execltext = "日志文件";
                    ExcelHelper hp = new ExcelHelper(saveFileDlg.FileName);
                    int rst = hp.DataTableToExcel(dt, execltext, true);
                    if (rst == -1)
                    {
                        MessageBox.Show("导出失败");
                    }
                    else
                    {
                        MessageBox.Show("导出成功");
                    }
                }
            }
        }
        //加载
        private void tabPage3_Click(object sender, EventArgs e)
        {
            string typetion = string.Format("select codeype,mationtype from Cardtype");
            SqlDataAdapter sda1 = new SqlDataAdapter(typetion, conn);
            DataSet ds = new DataSet();
            sda1.Fill(ds);
            System.Data.DataTable dt = ds.Tables[0];
            cxtype.DataSource = dt;
            cxtype.DisplayMember = dt.Rows[0]["mationtype"].ToString();
            cxtype.ValueMember = dt.Columns[1].ToString();
            conn.Close();
        }
        #endregion

        #region 密码修改
        //确认修改密码
        private void pwdconfirm_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "密码修改")
            {
                //string str2 = string.Format("select type from Usermation where username='{0}'", uname);
                //SqlDataAdapter sda = new SqlDataAdapter(str2, conn);
                //DataTable dt = new DataTable();
                //sda.Fill(dt);
                //if (dt.Rows[0]["type"].ToString() == "超级管理员")
                //{
                //    string uname = userInfo.userName;
                //    conn.Open();
                //    if (oldpwd.Text != "")
                //    {
                //        string str = string.Format("select pwd from Usermation where username='{0}'", uname);
                //        SqlDataAdapter sdapass = new SqlDataAdapter(str, conn);
                //        DataTable dtpass = new DataTable();
                //        sdapass.Fill(dtpass);
                //        string upass = dtpass.Rows[0]["pwd"].ToString();
                //        if (oldpwd.Text == upass)
                //        {
                            if (newpwd.Text == confirmpwd.Text)
                            {
                                SqlParameter[] param = new SqlParameter[] {
                                    new SqlParameter("@username",uname),
                                    new SqlParameter("@oldpwd",oldpwd.Text),
                                    new SqlParameter("@newpwd",newpwd.Text)
                                };
                                int i = DBHelper.ExecuteNonQuery("ExitPassWord", param, CommandType.StoredProcedure);
                                //string str1 = string.Format("update Usermation set pwd='{0}' where username='{1}'", newpwd.Text, uname);
                                //SqlCommand cmd = new SqlCommand(str1, conn);
                                //int i = cmd.ExecuteNonQuery();
                                if (i > 0)
                                {
                                    MessageBox.Show("账户:'" + uname + "'\n密码已修改!");
                                    oldpwd.Text = "";
                                    newpwd.Text = "";
                                    confirmpwd.Text = "";
                                }
                            }
                            else
                            {
                                MessageBox.Show("两次密码输入不一致,请重新确认密码!");
                                confirmpwd.Text = "";
                                newpwd.Text = "";
                                newpwd.Focus();
                            }
                        }
                //        else
                //        {
                //            MessageBox.Show("原始密码错误,请重新输入!");
                //            oldpwd.Text = "";
                //            oldpwd.Focus();
                //        }
                //    }
                //    else
                //    {
                //        MessageBox.Show("原始密码不能为空,请输入!");
                //        oldpwd.Focus();
                //    }
                //    conn.Close();
                //}
                //else
                //{
                //    MessageBox.Show("你没有该权限!");
                //}
            //}
        }
        //取消修改
        private void cancelpass_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "密码修改")
            {
                oldpwd.Text = "";
                newpwd.Text = "";
                confirmpwd.Text = "";
            }
        }
        #endregion

        #region 角色分配
        //角色分配确认
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "角色分配")
            {
                if (fputype.SelectedIndex == 0)
                {
                    MessageBox.Show("请选择管理员类别!");
                }
                else
                {
                    SqlParameter[] param = new SqlParameter[] {
                    new SqlParameter("@username",fpuname.Text.Trim()),
                    new SqlParameter("@pwd",fpupwd.Text.Trim()),
                    new SqlParameter("@type",fputype.Text)
                };
                    int i = DBHelper.ExecuteNonQuery("RoleAssignment", param, CommandType.StoredProcedure);
                    if (i > 0)
                    {
                        MessageBox.Show("角色:'" + fpuname.Text + "'\n已被添加为'" + fputype.Text + "'");
                        fpuname.Text = "";
                        fpupwd.Text = "";
                        fputype.SelectedIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show("你没有该权限!");
                        fpuname.Text="";
                        fpupwd.Text = "";
                        fputype.SelectedIndex = 0;    
                    }
                }
            }
        }
        //取消角色分配
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "角色分配")
            {
                fpuname.Text = "";
                fpupwd.Text = "";
                fputype.SelectedIndex = 0;
            }
        }
        #endregion

        //选项卡改变
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Text == "建卡")
            {
               jkthecard.Enabled=jkcancel.Enabled = jkquery.Enabled=jkconcellation.Enabled = false;
            }
            if (this.tabControl1.SelectedTab.Text == "消费")
            {
                xfconfirm.Enabled = xfcancel.Enabled = xfquery.Enabled = false;
                this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", 200, 1800);
            }
            if (this.tabControl1.SelectedTab.Text == "查询打印")
            {
                string typetion = string.Format("select codeype,mationtype from Cardtype");
                SqlDataAdapter sda1 = new SqlDataAdapter(typetion, conn);
                DataSet ds = new DataSet();
                sda1.Fill(ds);
                System.Data.DataTable dt = ds.Tables[0];
                DataRow newRow;
                newRow = dt.NewRow();
                newRow["mationtype"] = "--请选择--";
                newRow["codeype"] = "0";
                dt.Rows.InsertAt(newRow, 0);
                cxtype.DataSource = dt;
                cxtype.DisplayMember = dt.Rows[0]["mationtype"].ToString();
                cxtype.ValueMember = dt.Columns[1].ToString();
                conn.Close();
            }
            if(this.tabControl1.SelectedTab.Text=="角色分配")
            {
                fputype.SelectedIndex = 0;
            }
        }
        //页面加载
        private void Mations_Load(object sender, EventArgs e)
        {
           jkthecard.Enabled=jkcancel.Enabled = jkquery.Enabled = jkconcellation.Enabled =jkrecharge.Enabled= jkchange.Enabled= false;
        }
    }
}
    

